//
//  HJShareController.m
//  KaiChat
//
//  Created by lx on 2024/3/6.
//

#import "HJShareController.h"
#import "HJShareToSessionController.h"
#import "HJShareToGroupController.h"
#import "HJShareToFriendController.h"
#import "HJShareSendMessageInputBar.h"
#import "HJShareSendMessageView.h"
#import "TUIDefine.h"
#import "HJShareModel.h"
#import "HJTimer.h"
#import "HJIM.h"
#import "HJChatMessageModel.h"
#import "HJAlertController.h"

@interface HJShareController ()<HJShareSendMessageViewDelegate>

@property (nonatomic, strong) NSArray *types;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) HJShareSendMessageView *sendMessageView;

@property (nonatomic, weak) UISegmentedControl *segmentedControl;
@property (nonatomic, strong) UIView *segmentedView;
@property (nonatomic, assign) CGFloat segmentedViewH;
@property (nonatomic, assign) CGFloat sendMessageViewH;
@property (nonatomic, strong) NSMutableArray *selectModels;
@property (nonatomic, strong) HJTimer *timer;
@property (nonatomic, strong) NSMutableArray *shareObjects;

@end

@implementation HJShareController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationBar.title = @"Share To";
    IQKeyboardManager.sharedManager.enable = NO;
    
    _sendMessageViewH = 90 + TabbarSafeBottomMargin;
    _segmentedViewH = 60 + TabbarSafeBottomMargin;
    
    self.view.backgroundColor = UIColor.whiteColor;
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, KNavBarHight, KScreenWidth, KScreenHeight - KNavBarHight - 60 - TabbarSafeBottomMargin)].addTo(self.view);
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces = NO;
    _scrollView.scrollEnabled = NO;
    _scrollView.backgroundColor = UIColor.whiteColor;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * self.types.count - 1, _scrollView.frame.size.height);
    
    TJWeakify(self)
    [self.types enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj[@"controller"]) {
            HJShareToSessionController *listController = obj[@"controller"];
            [self addChildViewController:listController];
            [self.scrollView addSubview:listController.view];
            listController.view.frame = CGRectMake(KScreenWidth * idx, 0, KScreenWidth, _scrollView.tj_height);
            [listController setSelectDidChangeBlock:^(NSArray * _Nonnull selectModels) {
                [weakself setSelectDidChange:selectModels];
            }];
            [listController setTextFieldBeginDidEditBlock:^{
                weakself.sendMessageView.responseKeyboard = NO;
                [weakself.sendMessageView reset];
            }];
            
            [listController setTextFieldEndDidEditBlock:^{
                weakself.sendMessageView.responseKeyboard = YES;
            }];
        }
    }];
    
    [self addSegmentedControl];
    [self addSendMessageView];
    [self showSegmentedControl];
}

- (void)showSegmentedControl {
    _segmentedView.hidden = NO;
    _sendMessageView.hidden = YES;
    [_sendMessageView resignFirstResponder];
    _scrollView.frame = CGRectMake(0, KNavBarHight, self.view.frame.size.width, self.view.frame.size.height - _segmentedViewH - KNavBarHight);
    _segmentedView.frame = CGRectMake(0, self.view.frame.size.height - _segmentedViewH, self.view.frame.size.width, _segmentedViewH);
}

- (void)showSendMessageView {
    _segmentedView.hidden = YES;
    _sendMessageView.hidden = NO;
    _scrollView.frame = CGRectMake(0, KNavBarHight, self.view.frame.size.width, self.view.frame.size.height - _sendMessageViewH - KNavBarHight);
    _sendMessageView.frame = CGRectMake(0, self.view.frame.size.height - _sendMessageViewH, self.view.frame.size.width, _sendMessageViewH);
}

- (void)addSegmentedControl {
    
    UIView *segmentedView = [UIView addToView:self.view];
    segmentedView.backgroundColor = UIColor.whiteColor;
    
    NSMutableArray *segmentedDatas = @[].mutableCopy;
    for (NSDictionary *dict in self.types) {
        [segmentedDatas addObject:dict[@"text"]];
    }
    
    UIView *segmentedContentView = [UIView addToView:segmentedView];
    segmentedContentView.backgroundColor = UIColor.whiteColor;
    [segmentedContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.bottom.inset(TabbarSafeBottomMargin);
    }];
    
    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentedDatas.copy];
    segmentedControl.selectedSegmentIndex = 0;
    [segmentedControl setDividerImage:[UIImage new] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    NSDictionary *normalAttributes = @{NSForegroundColorAttributeName: [UIColor tj_868391Color], NSFontAttributeName: UIFontMake(12)};
    [segmentedControl setTitleTextAttributes:normalAttributes forState:UIControlStateNormal];
    
    NSDictionary *selectedAttributes = @{NSForegroundColorAttributeName: [UIColor tj_333333Color], NSFontAttributeName: UIFontMediumMake(12)};
    [segmentedControl setTitleTextAttributes:selectedAttributes forState:UIControlStateSelected];
    
    [segmentedControl addTarget:self action:@selector(segmentedControlDidChange:) forControlEvents:UIControlEventValueChanged];
    [segmentedContentView addSubview:segmentedControl];
    [segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(56);
        make.centerY.offset(0);
        make.height.offset(40);
    }];
    
    
    UIView *lineView = [UIView addToView:segmentedView];
    lineView.backgroundColor = UIColor.tj_separatorColor;
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.offset(0);
        make.height.offset(lineHeight);
    }];
    
    _segmentedView = segmentedView;
    _segmentedControl = segmentedControl;
}

- (void)addSendMessageView {
    _sendMessageView = [[HJShareSendMessageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 90)];
    _sendMessageView.delegate = self;
    [self.view addSubview:_sendMessageView];
}

- (void)sendMessageView:(HJShareSendMessageView *)messageView didChangeHeight:(CGFloat)height {
    
    UIViewAnimationOptions animationOptions = 7 << 16;
    [UIView animateWithDuration:0.25 delay:0 options:animationOptions animations:^{
        CGRect msgFrame = self.scrollView.frame;
        msgFrame.size.height = self.view.frame.size.height - KNavBarHight - height;
        self.scrollView.frame = msgFrame;
        
        CGRect inputFrame = self.sendMessageView.frame;
        inputFrame.origin.y = msgFrame.origin.y + msgFrame.size.height;
        inputFrame.size.height = height;
        self.sendMessageView.frame = inputFrame;
        
        
    } completion:nil];
}

- (void)sendMessageView:(HJShareSendMessageView *)messageView didSendTextMessage:(NSString *)text {
    
    [self.shareObjects removeAllObjects];
    if (_objects) {
        [self.shareObjects addObjectsFromArray:_objects];
    }
    if (!isEmptyString(text)) {
        [self.shareObjects addObject:text];
    }
    
    if (self.shareObjects.count == 0) {
        [HJAlertController alertInController:self title:nil message:@"Unable to send blank message" left:nil right:^(HJAlertAction * _Nonnull action) {
            action.title = @"OK";
            action.titleColor = UIColor.tj_mainColor;
        }];
        return;
    }
    
    
    [self sendMessage];
}

- (HJChatMessageModel *)getMessageModelWithShareModel:(HJShareModel *)shareModel {
    
    HJChatMessageModel *messageModel = [[HJChatMessageModel alloc] init];
    
    if ([shareModel.anyObject isKindOfClass:HJChatSessionModel.class]) {
        
        HJChatSessionModel *sessionModel = shareModel.anyObject;
        messageModel.chatType = sessionModel.chatType;
        
        if (sessionModel.chatType == HJChatTypeSingle) {
            messageModel.sessionUserd = sessionModel.sessionUserd;
            messageModel.sessionId = sessionModel.sessionId;
            messageModel.receiverId = sessionModel.sessionUserd;
        } else {
            messageModel.sessionId = sessionModel.groupId;
            messageModel.groupId = sessionModel.groupId;
        }
        
    } else if ([shareModel.anyObject isKindOfClass:HJChatFriendModel.class]) {
        
        HJChatFriendModel *friendModel = shareModel.anyObject;
        messageModel.chatType = HJChatTypeSingle;
        messageModel.sessionUserd = friendModel.userId;
        messageModel.sessionId = friendModel.sessionId;
        messageModel.receiverId = friendModel.userId;
        
        NSLog(@"messageModel.sessionId = %@", messageModel.sessionId);
        
    } else if ([shareModel.anyObject isKindOfClass:HJChatGroupModel.class]) {
        
        HJChatGroupModel *groupModel = shareModel.anyObject;
        messageModel.chatType = HJChatTypeGroup;
        messageModel.groupId = groupModel.groupId;
        messageModel.sessionId = messageModel.groupId;
    }
    return messageModel;
}

- (void)sendMessage {
    
    NSLog(@"self.shareObjects = %@", self.shareObjects);
    
    [HJHUD showLoadingInView:self.view];
    
    dispatch_async_global_queue(^{
        
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
        
        for (int i = 0; i < self.selectModels.count; i++) {
            for (int j = 0; j < self.shareObjects.count; j++) {
                
                HJShareModel *shareModel = self.selectModels[i];
                HJChatMessageModel *messageModel = [self getMessageModelWithShareModel:shareModel];
                
                id anyObject = self.shareObjects[j];
                
                if ([anyObject isKindOfClass:UIImage.class]) {
                    
                    messageModel.originalImage = anyObject;
                    messageModel.messageType = HJMessageTypeImage;
                    
                    NSData *imageData = UIImageJPEGRepresentation(anyObject, 0.6);
                    
                    NSString *fileName = getFileNameWithPathExtension(@"jpg");;
                    NSString *localPath = [HJMessageFileManager imagefileFilePathWithSessionId:messageModel.sessionId fileName:fileName];
                    [HJTools writeImageData:imageData toLocalPath:localPath];
                    
                    messageModel.localPath = localPath;
                    messageModel.originalImage = anyObject;
                    messageModel.messageType = HJMessageTypeImage;
                    
                } else if ([anyObject isKindOfClass:NSURL.class]) {
                    
                    UIImage *originalImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:anyObject]];
                    if (originalImage) {
                        NSData *imageData = UIImageJPEGRepresentation(originalImage, 0.6);
                        UIImage *originalImage = [UIImage imageWithData:imageData];
                        
                        NSString *fileName = getFileNameWithPathExtension(@"jpg");;
                        NSString *localPath = [HJMessageFileManager imagefileFilePathWithSessionId:messageModel.sessionId fileName:fileName];
                        [HJTools writeImageData:imageData toLocalPath:localPath];
                        messageModel.localPath = localPath;
                        messageModel.originalImage = originalImage;
                        messageModel.messageType = HJMessageTypeImage;
                    }
                    
                } else if ([anyObject isKindOfClass:NSString.class]) {
                    messageModel.content = anyObject;
                    messageModel.messageType = HJMessageTypeText;
                } else {
                    continue;
                }
                
                dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                [[HJIM shareIM].chatManager sendMessageWithModel:messageModel begin:^{
                    [[NSNotificationCenter defaultCenter] postNotificationName:inserMessageNotification object:messageModel];
                    dispatch_semaphore_signal(semaphore);
                    if (self.shareObjects.count && i == self.selectModels.count - 1 && j == self.shareObjects.count - 1) {
                        dispatch_async_main_queue(^{
                            [HJHUD hiddenLoadingInView:self.view];
                            [HJHUD showSucceedMessage:@"Share Succeed"];
                            [self dismissViewControllerAnimated:YES completion:self.succeedBlock];
                        });
                    }
                } completion:^(id  _Nullable response, NSError * _Nullable error) {
                    
                }];
            }
        }
        
    });
    
    
    
    
}

- (void)segmentedControlDidChange:(UISegmentedControl *)sender {
    NSUInteger index = [sender selectedSegmentIndex];
    
    NSDictionary *dict = self.types[index];
    NSString *type = dict[@"type"];
    if ([type isEqualToString:@"more"]) {
        
        NSArray *array = nil;
        if ([_objects.firstObject isKindOfClass:UIImage.class]) {
            array = @[_objects.firstObject];
        } else if ([_objects.firstObject isKindOfClass:NSURL.class]) {
            array = @[_objects.firstObject];
        } else if ([_objects.firstObject isKindOfClass:NSString.class]) {
            NSString *url = _objects.firstObject;
            array = @[[NSURL URLWithString:url]];
        }
        NSLog(@"_objects = %@", _objects);
        
        UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:array applicationActivities:nil];
        activityViewController.excludedActivityTypes = @[UIActivityTypeMessage];
        activityViewController.completionWithItemsHandler = ^(UIActivityType __nullable activityType, BOOL completed, NSArray * __nullable returnedItems, NSError * __nullable activityError){
            if (self.succeedBlock) {
                self.succeedBlock();
            }
        };
        [self presentViewController:activityViewController animated:YES completion:nil];
        return;
    }
    
    [self.scrollView setContentOffset:CGPointMake(KScreenWidth * index, 0)];
}


- (void)setSelectDidChange:(NSArray *)selectModels {
    
    [self.selectModels removeAllObjects];
    if (selectModels.count) {
        [self.selectModels addObjectsFromArray:selectModels];
    }
    _sendMessageView.inputBar.count = selectModels.count;
    if (selectModels.count) {
        [self showSendMessageView];
    } else {
        [self showSegmentedControl];
    }
}

- (NSMutableArray *)selectModels {
    if (!_selectModels) {
        _selectModels = [NSMutableArray array];
    }
    return _selectModels;
}

- (NSArray *)types {
    if (!_types) {
        _types = @[
            @{
                @"text": @"Chats",
                @"type": @"chats",
                @"controller": [[HJShareToSessionController alloc] init],
            },
            @{
                @"text": @"Friends",
                @"type": @"friends",
                @"controller": [[HJShareToFriendController alloc] init],
            },
            @{
                @"text": @"Groups",
                @"type": @"groups",
                @"controller": [[HJShareToGroupController alloc] init],
            },
            @{
                @"text": @"More",
                @"type": @"more",
            }
        ];
    }
    return _types;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    IQKeyboardManager.sharedManager.enable = YES;
}

- (NSMutableArray *)shareObjects {
    if (!_shareObjects) {
        _shareObjects = [NSMutableArray array];
    }
    return _shareObjects;
}

- (HJTimer *)timer {
    if (!_timer) {
        _timer = [HJTimer timer];
    }
    return _timer;
}

- (void)dealloc {
    if (self.popBlock) {
        self.popBlock();
    }
    NSLog(@"%s", __func__);
}


- (UIModalPresentationStyle)modalPresentationStyle {
    return UIModalPresentationFullScreen;
}

@end
